const express = require('express');
const cors = require('cors');
const fs = require('fs').promises;
const path = require('path');
const app = express();
const port = 3000;

// 启用 CORS 和 JSON 解析
app.use(cors());
app.use(express.json());

// 新增：静态文件服务
app.use(express.static(path.join(__dirname)));

// 数据文件路径
const DATA_FILE = path.join(__dirname, 'data', 'users.json');

// 确保数据目录存在
async function ensureDataDir() {
    try {
        await fs.mkdir(path.join(__dirname, 'data'), { recursive: true });
        try {
            await fs.access(DATA_FILE);
        } catch {
            await fs.writeFile(DATA_FILE, JSON.stringify({ users: {} }));
        }
    } catch (error) {
        console.error('Error initializing data directory:', error);
    }
}

// 读取用户数据
async function readUserData() {
    try {
        const data = await fs.readFile(DATA_FILE, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        console.error('Error reading user data:', error);
        return { users: {} };
    }
}

// 保存用户数据
async function saveUserData(data) {
    try {
        await fs.writeFile(DATA_FILE, JSON.stringify(data, null, 2));
        return true;
    } catch (error) {
        console.error('Error saving user data:', error);
        return false;
    }
}

// 获取用户数据
app.get('/api/users/:username', async (req, res) => {
    try {
        const data = await readUserData();
        const user = data.users[req.params.username];
        if (user) {
            res.json({ success: true, data: user });
        } else {
            res.status(404).json({ success: false, message: 'User not found' });
        }
    } catch (error) {
        res.status(500).json({ success: false, message: 'Server error' });
    }
});

// 保存用户数据
app.post('/api/users/:username', async (req, res) => {
    try {
        const data = await readUserData();
        data.users[req.params.username] = req.body;
        const success = await saveUserData(data);
        console.log('注册返回：', success);
        if (success) {
            res.json({ success: true });
        } else {
            res.status(500).json({ success: false, message: 'Failed to save data' });
        }
    } catch (error) {
        res.status(500).json({ success: false, message: 'Server error' });
    }
});

// 初始化数据目录并启动服务器
ensureDataDir().then(() => {
    app.listen(port, () => {
        console.log(`Server running at http://localhost:${port}`);
    });
}); 